package com.mobartisan.workinglunch.widget;

import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.mobartisan.workinglunch.R;
import com.mobartisan.workinglunch.SnakeApplication;
import com.mobartisan.workinglunch.network.action.SnakeAction;
import com.mobartisan.workinglunch.network.action.impl.SnakeActionImpl;
import com.orhanobut.logger.Logger;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import rx.Subscriber;

import static com.igexin.push.core.a.i;


public class DownloadFilePopupDialog extends Dialog implements OnClickListener {
    private static final String TAG = DownloadFilePopupDialog.class.getSimpleName();
    private static final int MSG_DOWNLOADING = 1;
    /* 下载结束 */
    private static final int MSG_DOWNLOAD_FINISH = 2;
    private Context context;
    private CallbackAction<Boolean> okHandler;
    private String remoteUrl;
    private String localPath;
    private Handler handler;
    private boolean cancelUpdate = false;
    private DownloadFileThread downloadFileThread;
    private int progress = 0;
    private boolean success = false;
    private boolean isShouldUpdate = false;// 是否强制更新

    private TextView tv_dialog_title, com_alert_cancel, tv_prog;
    private ProgressBar update_progress;

    public DownloadFilePopupDialog(Context context) {
        super(context, R.style.mystyle);
        this.context = context;
        this.initDialog();
    }

    protected void initDialog() {
        this.setContentView(R.layout.view_progress);
        Window dialogWindow = this.getWindow();
        tv_dialog_title = (TextView) dialogWindow.findViewById(R.id.tv_dialog_title);
        com_alert_cancel = (TextView) dialogWindow.findViewById(R.id.com_alert_cancel);
        tv_prog = (TextView) dialogWindow.findViewById(R.id.tv_prog);
        update_progress = (ProgressBar) dialogWindow.findViewById(R.id.update_progress);
        com_alert_cancel.setOnClickListener(this);
        this.setCancelable(false);
        this.setCanceledOnTouchOutside(false);
        this.handler = new Handler((msg) -> {

            switch (msg.what) {
                // 正在下载
                case MSG_DOWNLOADING:
                    // 设置进度条位置
                    update_progress.setProgress(progress);
                    tv_prog.setText(progress + " %");
                    break;
                case MSG_DOWNLOAD_FINISH:
                    onDownloadFinished();
                    break;
                default:
                    break;
            }
            return false;

        });
    }

    public void init(String tipTitle, boolean isShouldUpdate, String remoteUrl, String localPath, CallbackAction<Boolean> handler) {
        tv_dialog_title.setText(tipTitle);
        this.isShouldUpdate = isShouldUpdate;
        this.setOnOkHandler(handler);
        this.remoteUrl = remoteUrl;
        this.localPath = localPath;
    }

    /**
     * 开始下载
     *
     * @return
     */
    public boolean startDownload() {
        if (this.downloadFileThread != null && this.downloadFileThread.isAlive())
            return false;
        cancelUpdate = false;
        progress = 0;
        this.show();
//        this.downloadFileThread = new DownloadFileThread();
//        this.downloadFileThread.start();
        getDownApk();
        return true;
    }

    public void setOnOkHandler(CallbackAction<Boolean> handler) {
        this.okHandler = handler;
    }

    @Override
    public void onClick(View v) {
        if (v == com_alert_cancel) {
            onCancelButtonClicked();
        }
    }

    protected void onDownloadFinished() {
        if (!success) {
            if (!cancelUpdate) {
                Toast.makeText(context, "对不起，下载失败!", Toast.LENGTH_SHORT).show();
                if (!isShouldUpdate) {
                    this.dismiss();
                }
            }

        } else {
            Toast.makeText(context, "下载成功!", Toast.LENGTH_SHORT).show();
            if (!isShouldUpdate) {
                this.dismiss();
            }
        }
        if (this.okHandler != null)
            this.okHandler.doAction(success);
    }

    protected void onCancelButtonClicked() {
        if (this.cancelUpdate)
            return;
        this.cancelUpdate = true;
//        this.downloadFileThread.interrupt();
        Toast.makeText(context, "您取消了下载!", Toast.LENGTH_SHORT).show();
        if (isShouldUpdate) {
            this.okHandler.doAction(false);
            SnakeApplication.getInstance().exitApp();
        } else if (this.okHandler != null)
            this.okHandler.doAction(false);
        this.dismiss();
    }

    /**
     * 请求蒲公英的apk下载接口.
     */

    protected void getDownApk() {
        OkHttpClient mHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(remoteUrl)
                .build();
        mHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream inputStream = null;
                FileOutputStream fos = null;
                inputStream = response.body().byteStream();

                // 获取文件大小
                long length = response.body().contentLength();
                // 创建输入流\
                File file = new File(localPath);
                // 判断文件目录是否存在
                if (!file.exists()) {
                    File parentDir = file.getParentFile();
                    if (!parentDir.exists())
                        parentDir.mkdirs();
                }
                fos = new FileOutputStream(file);
                int count = 0;
                // 缓存
                byte buf[] = new byte[1024];
                // 写入到文件中
                do {
                    int numread = inputStream.read(buf);
                    count += numread;
                    // 计算进度条位置
                    progress = (int) (((float) count / length) * 100);
                    // 更新进度
                    if (progress >= 0)
                        handler.sendEmptyMessage(MSG_DOWNLOADING);
                    if (numread <= 0) {
                        success = true;
                        break;
                    }
                    // 写入文件
                    fos.write(buf, 0, numread);
                } while (!cancelUpdate);// 点击取消就停止下载.
                handler.sendEmptyMessage(MSG_DOWNLOAD_FINISH);
            }
        });
    }

    /**
     * 下载文件线程
     *
     * @author coolszy
     * @date 2012-4-26
     * @blog http://blog.92coding.com
     */
    private class DownloadFileThread extends Thread {
        @Override
        public void run() {
            success = false;
            InputStream is = null;
            FileOutputStream fos = null;
            try {
                URL url = new URL(remoteUrl);
                // 创建连接
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.connect();
                // 获取文件大小
                int length = conn.getContentLength();
                // 创建输入流
                is = conn.getInputStream();
                File file = new File(localPath);
                // 判断文件目录是否存在
                if (!file.exists()) {
                    File parentDir = file.getParentFile();
                    if (!parentDir.exists())
                        parentDir.mkdirs();
                }
                fos = new FileOutputStream(file);
                int count = 0;
                // 缓存
                byte buf[] = new byte[1024];
                // 写入到文件中
                do {
                    int numread = is.read(buf);
                    count += numread;
                    // 计算进度条位置
                    progress = (int) (((float) count / length) * 100);
                    // 更新进度
                    if (progress >= 0)
                        handler.sendEmptyMessage(MSG_DOWNLOADING);
                    if (numread <= 0) {
                        success = true;
                        break;
                    }
                    // 写入文件
                    fos.write(buf, 0, numread);
                } while (!cancelUpdate);// 点击取消就停止下载.
            } catch (Exception error) {
                Logger.e(error);
            } finally {
                try {
                    safeClose(fos);
                    safeClose(is);
                } catch (Exception e) {
                    Logger.e(e);
                }
            }
            // 下载完成
            handler.sendEmptyMessage(MSG_DOWNLOAD_FINISH);
        }
    }

    public static void safeClose(InputStream fis) {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                Log.d(TAG, "safeClose: ");
            }
        }
    }

    public static void safeClose(OutputStream iis) {
        if (iis != null) {
            try {
                iis.close();
            } catch (IOException e) {
                Log.d(TAG, "safeClose: ");
            }
        }
    }
}
